package br.fxfc.android.daysuntil;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

public class List extends Activity implements OnItemLongClickListener {

	private static final int menuAdd = 0x0000;
	private TextView textList;
	private ListView listView;
	private SQLiteDatabase dbReadOnly;
	private DBHelper db;
	private Cursor list;
	private MyCursorAdapter mca;

	private String TAG = "List";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Pega referências
		textList = (TextView) findViewById(R.id.textList);
		listView = (ListView) findViewById(R.id.listView);

		// Inicia valores padrão
		textList.setText("teste");

		initDB();
		
		listView.setOnItemLongClickListener(this);
		
//		TimerTask tt = new UpdateListTask(list, mca);
//		
//		Timer t = new Timer();
//		
//		t.schedule(tt, 10, 10);
	}

	private void initDB() {
		// Inicia banco de dados
		db = new DBHelper(this);

		// Pegar referencia de leitura no banco de dados
		dbReadOnly = db.getReadableDatabase();

		list = dbReadOnly.query(DBHelper.TableDaysUntil.NAME, null, null, null,
				null, null, null);
		startManagingCursor(list);

		String[] from = { DBHelper.TableDaysUntil.COL_TEXT,
				DBHelper.TableDaysUntil.COL_DATETIME };
		int[] to = { R.id.textEvent, R.id.textDate };

		mca = new MyCursorAdapter(this, R.layout.item, list, from, to);

		listView.setAdapter(mca);

	}

	@Override
	protected void onDestroy() {
		Log.d(TAG, "onDestroy(): enter");

		stopManagingCursor(list);
		dbReadOnly.close();
		super.onDestroy();

		Log.d(TAG, "onDestroy(): exit");
	}

	@Override
	protected void onResume() {
		Log.d(TAG, "onResume(): enter");

		list.requery();
		mca.notifyDataSetChanged();
		super.onResume();

		Log.d(TAG, "onResume(): exit");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, menuAdd, 0, R.string.menuAdd);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case menuAdd:
			Intent i = new Intent(this, Add.class);
			startActivity(i);
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {


		return false;
	}
}